Page({
  data: {
    books: [],
    filePath: "",
    keyword: "",
    history: wx.getStorageSync("history") || [],
  },
  // 1. 获取书单列表
  getBooks() {
    // 1.1 提示加载
    wx.showLoading({
      title: "正在加载中...",
      mask: true,
    });
    // 1.2 调用接口
    wx.request({
      url: "https://hmajax.itheima.net/api/books",
      method: "GET",
      data: { creator: "zhangsan" },
      header: {},
      success: (res) => {
        console.log(res);
        this.setData({
          books: res.data.data,
        });
        // 1.4 消息提示框(轻提示)
        wx.showToast({
          title: "获取数据成功",
          icon: "none",
        });
      },
      fail: () => {},
      complete: () => {
        // 1.3 关闭消息提示框
        wx.hideLoading();
      },
    });
  },
  // ---------------数据的本地存储操作
  setStorage() {
    wx.setStorageSync("author", "不知火舞");
    wx.setStorageSync("user", { name: "张三", age: 18, gender: "男" });
  },
  getStorage() {
    const author = wx.getStorageSync("author");
    console.log(author);
    const user = wx.getStorageSync("user");
    console.log(user);
  },
  delStorage() {
    wx.removeStorageSync("logs");
  },
  clearStorage() {
    wx.clearStorageSync();
  },
  // -----------------测试async/await的使用
  async chooseImage() {
    const res = await wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      // success: (res) => {
      //   console.log(res);
      //   this.setData({
      //     filePath: res.tempFiles[0].tempFilePath,
      //   });
      // },
    });
    // console.log(res);
    this.setData({
      filePath: res.tempFiles[0].tempFilePath,
    });
  },
  // --------------------------------
  searchByKeyword() {
    // 1.1 取出关键字放入数组
    const { keyword, history } = this.data;
    history.push(keyword);
    this.setData({ history, keyword: "" });

    // 1.2 本地持久化
    wx.setStorageSync("history", history);
  },
});
